package com.atguigu.exam.service.impl;

import com.atguigu.exam.entity.Banner;
import com.atguigu.exam.mapper.BannerMapper;
import com.atguigu.exam.service.BannerService;

import com.atguigu.exam.service.FileUploadService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.minio.Result;
import io.minio.errors.*;
import io.netty.util.internal.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 轮播图服务实现类
 */
@Slf4j
@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {

    @Autowired
    private FileUploadService fileUploadService;

    @Override
    public String uploadBannerImage(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //判断是否为空
        if(file.isEmpty()){
            throw new RuntimeException("上传的轮播图图片为空！上传失败");
        }
        //判断是否是图片类型
        String contentType = file.getContentType();
        if(ObjectUtils.isEmpty(contentType)||!contentType.startsWith("image")){
            throw new RuntimeException("上传轮播图文件类型错误！上传失败");
        }
        //进行上传
        String imageUrl = fileUploadService.uploadFile(file, "banners");
        //返回
        return imageUrl;
    }

    /**
     * 添加轮播图
     * @param banner
     */
    @Override
    public void addBanner(Banner banner) {
        boolean save = save(banner);
        if(save) {
            log.info("轮播图保存成功");
        }
    }

    /**
     * 更新轮播图
     * @param banner
     */
    @Override
    public void updateBanner(Banner banner) {
        this.updateById(banner);

    }

    /**
     * 删除轮播图
     * @param id
     */
    @Override
    public void deleteBanner(Long id) {
        this.removeById(id);
    }
}